import path from 'path';

import type { Plugin } from 'vite';

type Append = Record<'headers' | 'footers' | 'scriptSetups', string[]>;

export function MarkdownTransform(): Plugin {
    return {
        name: 'md-transform',
        enforce: 'pre',
        async transform(code, id) {
            if (id.endsWith('.md') && id.includes('/ui-vue/docs/components')) {
                const pathFragements = id.split('/');
                const componentName = pathFragements[pathFragements.length - 2];
                const append: Append = {
                    headers: [],
                    footers: [],
                    scriptSetups: [`const demos = import.meta.globEager('../../../demos/${componentName}/*.vue')`]
                };
                // code = transformVpScriptSetup(code, append);
                return combineMarkdown(code, [combineScriptSetup(append.scriptSetups), ...append.headers], append.footers);
            }
        }
    };
}

const combineScriptSetup = (codes: string[]) =>
    `\n<script setup lang="ts">
${codes.join('\n')}
</script>
`;

const combineMarkdown = (code: string, headers: string[], footers: string[]) => {
    const frontmatterEndsPosition = code.indexOf('---\n\n');
    const frontmatterEnds = frontmatterEndsPosition > -1 ? frontmatterEndsPosition + 4 : 0;
    // const firstSubheader = code.search(/\n## \w/);
    const firstSubheader = code.search(/\n##/);
    const sliceIndex = firstSubheader < 0 ? frontmatterEnds : firstSubheader;

    if (headers.length > 0) code = code.slice(0, sliceIndex) + headers.join('\n') + code.slice(sliceIndex);
    code += footers.join('\n');

    return `${code}\n`;
};

const vpScriptSetupRE = /<vp-script\s(.*\s)?setup(\s.*)?>([\s\S]*)<\/vp-script>/;

const transformVpScriptSetup = (code: string, append: Append) => {
    const matches = code.match(vpScriptSetupRE);
    if (matches) code = code.replace(matches[0], '');
    const scriptSetup = matches?.[3] ?? '';
    if (scriptSetup) append.scriptSetups.push(scriptSetup);
    return code;
};
